package com.hmall.item.task;

import com.hmall.common.client.OrderClient;
import com.hmall.common.dto.OrderDetail;
import com.hmall.common.pojo.Order;
import com.hmall.item.pojo.Restore;
import com.hmall.item.service.impl.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @Author whx
 * @Date 2024/11/15 23:19
 */
@Component
public class CleanNonPaymentTask {

    @Autowired
    private OrderClient orderClient;

    @Autowired
    private ItemService itemService;

    @Scheduled(cron = "0 * * * * ?")
    public void clean(){
        // 查询超时订单
        List<Order> orders = orderClient.selectList();

        if(!orders.isEmpty()){
            // 不为空，恢复库存
            for (Order order : orders) {

//                 根据订单id查询订单详情
                List<OrderDetail> orderDetails = orderClient.queryOrderDetailById(order.getId());
//                List<Order> orderDetails = orderClient.queryOrderDetailById(order.getId());

                List<Restore> collect = orderDetails.stream().map(orderDetail -> new Restore().builder()
                        .itemId(orderDetail.getItemId())
                        .num(orderDetail.getNum())
                        .build()).collect(Collectors.toList());

                itemService.restore(collect);

                orderClient.updateOrder(order.getId());
            }
        }

    }

}
